package com.leyou.search.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.client.ItemClient;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.*;
import com.leyou.search.dto.GoodsDTO;
import com.leyou.search.dto.SearchRequest;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fenglin
 * @date 2019/12/14 15:54
 */
@Service
public class SearchService {

    @Autowired
    private ItemClient itemClient;

    public Goods buildGoods(SpuDTO spu) {
        //1.搜索字段，包括：名称、分类、品牌。。。
        //1.1查询分类
        String categoryName = spu.getCategoryName();
        if (StringUtils.isBlank(categoryName)) {
            //如果没有查询
            categoryName = itemClient.queryCategoryByIds(spu.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining());
        }
        //1.2查询品牌
        String brandName = spu.getBrandName();
        if (StringUtils.isBlank(brandName)) {
            //如果没有查询
            brandName = itemClient.queryBrandById(spu.getBrandId()).getName();
        }
        //1.3拼接
        String all = spu.getName() + " " + categoryName + " " + brandName;

        //2.spu下的sku的集合， 转JSON
        List<SkuDTO> skuDTOList = spu.getSkus();
        if (CollectionUtils.isEmpty(skuDTOList)) {
            skuDTOList = itemClient.querySkuBySpuId(spu.getId());
        }
        List<Map<String, Object>> skuList = new ArrayList<>(skuDTOList.size());

        //只需要4个，其他的过滤
        for (SkuDTO skuDTO : skuDTOList) {
            HashMap<String, Object> map = new HashMap<>(4);
            map.put("id", skuDTO.getId());
            map.put("title", skuDTO.getTitle());
            map.put("price", skuDTO.getPrice());
            map.put("image", StringUtils.substringBefore(skuDTO.getImages(), ","));
            skuList.add(map);
        }
        //3.sku的价格的集合
        Set<Long> prices = skuDTOList.stream().map(SkuDTO::getPrice).collect(Collectors.toSet());

        //4.规格参数，key：规格参数名称。 value：规格参数的值
        Map<String, Object> specs = new HashMap<>();
        // 4.1.查询规格参数名，作为specs的key，根据当前商品分类查询，查询的是searching为true（参与搜索）
        List<SpecParamDTO> specParams = itemClient.querySpecParams(null, spu.getCid3(), true);
        // 4.2.查询spuDetail，获取规格参数值，作为specs的value
        SpuDetailDTO spuDetail = spu.getSpuDetail();
        if (spuDetail == null) {
            spuDetail = itemClient.querySpuDetailById(spu.getId());
        }
        // 4.2.1.获取的是genericSpec的值
        Map<Long, Object> genericSpec = JsonUtils.toMap(spuDetail.getGenericSpec(), Long.class, Object.class);
        // 4.2.1.获取的是genericSpec的值
        Map<Long, Object> specialSpec = JsonUtils.toMap(spuDetail.getSpecialSpec(), Long.class, Object.class);
        // 4.2.3.合并规格值
        genericSpec.putAll(specialSpec);
        // 4.3.把key和value匹配，放入specs
        for (SpecParamDTO param : specParams) {
            // 取出参数名，作为key
            String key = param.getName();
            // 根据param的id从genericSpec取出value
            Object value = genericSpec.get(param.getId());
            // 判断value值是否是数字
            if (param.getNumeric()) {
                // 是数字，判断value在segment中的哪一个区间
                value = chooseSegment(value, param);
            }
            // 存
            specs.put(key, value);
        }
        //创建goods，并填写数据
        Goods goods = new Goods();
        goods.setSubTitle(spu.getSubTitle());
        goods.setId(spu.getId());
        goods.setCategoryId(spu.getCid3());
        goods.setBrandId(spu.getBrandId());

        // 搜索字段，包括：名称、分类、品牌。。。
        goods.setAll(all);
        goods.setCreateTime(System.currentTimeMillis());
        // sku的价格的集合
        goods.setPrice(prices);
        // spu下的sku的集合， 转JSON
        goods.setSkus(JsonUtils.toString(skuList));
        // 规格参数，key：规格参数名称。 value：规格参数的值
        goods.setSpecs(specs);
        return goods;
    }

    private Object chooseSegment(Object value, SpecParamDTO p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = 0;
        try {
            val = parseDouble(value.toString());
        } catch (Exception e) {
            return value;
        }
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        return Double.parseDouble(str);
    }

    @Autowired
    private ElasticsearchTemplate esTemplate;

    public PageResult<GoodsDTO> searchGoods(SearchRequest request) {
        // 1.原生查询得构建器工厂
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 2.构建查询条件
        // 2.1.source过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "subTitle", "skus"}, new String[0]));
        // 2.2.条件过滤
        queryBuilder.withQuery(buildBasicQuery(request));
        // 2.3.分页
        queryBuilder.withPageable(PageRequest.of(request.getPage() - 1, request.getSize()));

        // 3.查询结果
        SearchQuery query = queryBuilder.build();
        AggregatedPage<Goods> result = esTemplate.queryForPage(query, Goods.class);

        // 4.解析结果
        // 4.1.分页数据
        long total = result.getTotalElements();
        int totalPage = result.getTotalPages();
        List<Goods> list = result.getContent();
        // 4.2.DTO转换
        List<GoodsDTO> dtoList = BeanHelper.copyWithCollection(list, GoodsDTO.class);

        // 5.封装并返回
        return new PageResult<>(total, totalPage, dtoList);
    }

    private BoolQueryBuilder buildBasicQuery(SearchRequest request) {
        // 非空判断
        if (StringUtils.isBlank(request.getKey())) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 构建布尔查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 添加must条件，关键字搜索
        boolQuery.must(QueryBuilders.matchQuery("all", request.getKey()));
        // 添加过滤条件
        Map<String, String> map = request.getFilter();
        if (!CollectionUtils.isEmpty(map)) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                if ("品牌".equals(key)) {
                    key = "brandId";
                } else if ("分类".equals(key)) {
                    key = "categoryId";
                } else {
                    key = "specs." + key;
                }
                boolQuery.filter(QueryBuilders.termQuery(key, entry.getValue()));
            }
        }
        return boolQuery;
    }

    public Map<String, List<?>> searchFilters(SearchRequest request) {
        // 1.原生查询得构建器工厂
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 2.构建查询条件
        // 2.1.source过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[0], new String[0]));
        // 2.2.条件过滤
        queryBuilder.withQuery(buildBasicQuery(request));
        // 2.3.分页
        queryBuilder.withPageable(PageRequest.of(0, 1));

        // 3.添加聚合条件
        // 3.1.添加分类的聚合
        queryBuilder.addAggregation(AggregationBuilders.terms("category_agg").field("categoryId"));
        // 3.2.添加品牌的聚合
        queryBuilder.addAggregation(AggregationBuilders.terms("brand_agg").field("brandId").size(50));

        // 4.发起请求，得到结果
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);

        // 5.获取聚合结果
        Aggregations aggregations = result.getAggregations();

        // 6.处理分类聚合
        Map<String, List<?>> filters = new LinkedHashMap<>();
        // 6.1.从聚合结果中获取id
        List<Long> categoryIdList = getIdsFromAggregation(aggregations, "category_agg");
        // 6.3.根据id查询数据
        List<CategoryDTO> categoryList = itemClient.queryCategoryByIds(categoryIdList);
        // 6.4.把结果封装
        filters.put("分类", categoryList);

        // 7.处理分类聚合
        // 7.1.从聚合结果中获取id
        List<Long> brandIdList = getIdsFromAggregation(aggregations, "brand_agg");
        // 7.2.根据id查询数据
        List<BrandDTO> brandList = itemClient.queryBrandByIds(brandIdList);
        // 7.3.把结果封装
        filters.put("品牌", brandList);

        // 8.判断分类id是否唯一，对分类下的规格参数聚合
        if (categoryIdList.size() == 1) {
            handleSpecAggregation(categoryIdList.get(0), request, filters);
        }
        return filters;
    }
    private void handleSpecAggregation(Long cid, SearchRequest request, Map<String, List<?>> filters) {
        // 1.根据分类查询参数名称，是这个分类下的，searching为true的参数
        List<SpecParamDTO> specParams = itemClient.querySpecParams(null, cid, true);

        // 2.准备查询条件（与搜索数据的条件一致）
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 2.1.source过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[0], new String[0]));
        // 2.2.条件过滤
        queryBuilder.withQuery(buildBasicQuery(request));
        // 2.3.分页
        queryBuilder.withPageable(PageRequest.of(0, 1));

        // 3.添加聚合条件
        for (SpecParamDTO param : specParams) {
            // 获取参数名称，作为聚合名称
            String name = param.getName();
            queryBuilder.addAggregation(AggregationBuilders.terms(name).field("specs." + name));
        }

        // 4.发起请求
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);
        // 5.解析聚合结果
        Aggregations aggregations = result.getAggregations();

        for (SpecParamDTO param : specParams) {
            String name = param.getName();
            // 根据聚合名称，获取聚合结果
            Terms terms = aggregations.get(name);
            // 从聚合结果中得到buckets
            // 从buckets中获取key，就是尺寸的字符串，变成字符串集合
            List<String> list = terms.getBuckets()
                    .stream()
                    .map(Terms.Bucket::getKeyAsString)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            // 把key（规格参数的名称）和 字符串集合存入map
            filters.put(name, list);
        }
    }
    private List<Long> getIdsFromAggregation(Aggregations aggregations, String category_agg) {
        // 6.1.根据聚合名称，获取聚合结果
        Terms categoryTerms = aggregations.get(category_agg);
        // 6.2.获取terms中的bucket，解析其中的id的集合
        return categoryTerms.getBuckets()
                .stream()
                .map(Terms.Bucket::getKeyAsNumber)
                .map(Number::longValue)
                .collect(Collectors.toList());
    }

    @Autowired
    private GoodsRepository goodsRepository;

    public void addGoods(Long spuId) {
        // 查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);
        // 构建一个Goods
        Goods goods = buildGoods(spu);
        // 保存到索引库
        goodsRepository.save(goods);
    }

    public void deleteGoods(Long spuId) {
        goodsRepository.deleteById(spuId);
    }
}
